<template>
  <div style="margin-top: 10px">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="search-card-title">Condition Search</span>
        </div>
      </template>
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline" ref="searchInfo">
        <el-row>
          <el-form-item label="Phone:" prop="phones">
            <el-select style="width: 440px" v-model="searchInfo.phones" multiple filterable remote allow-create
              default-first-option placeholder="please input phone number">
              <el-option v-for="item in phones" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-form-item label="Role:" prop="roles">
            <el-select style="width: 220px" v-model="searchInfo.roles" multiple filterable allow-create
              default-first-option placeholder="please select role">
              <el-option label="User" value="user"></el-option>
              <el-option label="Auditor" value="auditor"></el-option>
              <el-option label="Administrator" value="administrator"></el-option>
            </el-select>
          </el-form-item>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-form-item label="Registration Time:" prop="createTime">
            <el-date-picker v-model="searchInfo.createTime" type="daterange" range-separator="to"
              start-placeholder="Start time" end-placeholder="End time" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-form-item label="Status:" prop="status">
            <el-select style="width: 220px" v-model="searchInfo.status" placeholder="please select status">
              <el-option label="Activation" value="activation"></el-option>
              <el-option label="Frozen" value="frozen"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="6" :offset="18" style="text-align: end; padding-top: 10px; padding-right: 10px">
            <el-button type="primary" size="mini" @click="searchForm()">SEARCH</el-button>
            <el-button type="info" size="mini" @click="resetForm('searchInfo')">RESET</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <br />
    <el-row>
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span class="search-card-title">User Information</span>
              <el-col :span="6" :offset="16" style="text-align: end; padding-right: 10px">
                <el-button size="medium" type="danger" icon="el-icon-delete" @click="batchDelete()">Batch Delete
                </el-button>
                <el-button icon="el-icon-download" @click="exportToExcel">Export to Excel</el-button>
              </el-col>
            </div>
          </template>
          <el-table :data="list" style="width: 100%" row-key="id" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="45"> </el-table-column>
            <el-table-column prop="phone" label="Phone" width="180">
            </el-table-column>
            <el-table-column prop="nickname" label="Nickname" width="150">
            </el-table-column>
            <el-table-column prop="email" label="Email" width="240">
            </el-table-column>
            <el-table-column label="Role" width="120">
              <template slot-scope="scope">
                <div>
                  <el-tag type="primary" size="medium" v-if="scope.row.role == 'user'">{{ scope.row.role }}</el-tag>
                  <el-tag type="success" size="medium" v-if="scope.row.role == 'administrator'">{{ scope.row.role }}
                  </el-tag>
                  <el-tag type="warning" size="medium" v-if="scope.row.role == 'auditor'">{{ scope.row.role }}</el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="Create Time" width="180" sortable>
            </el-table-column>
            <el-table-column prop="status" label="Status" width="180">
              <template slot-scope="scope">
                <div>
                  <el-tag type="primary" v-if="scope.row.status == 'frozen'">{{
                      scope.row.status
                  }}</el-tag>
                  <el-tag type="success" v-if="scope.row.status == 'activation'">{{ scope.row.status }}</el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="totalQuestionnaires" label="Total Questionnaires" width="170">
            </el-table-column>

            <el-table-column label="Operations">
              <template slot-scope="scope">
                <el-button size="mini" type="success" icon="el-icon-folder-checked"
                  @click="handleDetail(scope.$index, scope.row)">Detail</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete"
                  @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
                <el-button v-if="scope.row.status == 'activation'" type="primary" size="mini" icon="el-icon-lock"
                  @click="handleLock(scope.row.id)">frozen</el-button>
                <el-button v-if="scope.row.status == 'frozen'" type="success" size="mini" icon="el-icon-unlock"
                  @click="handleLock(scope.row.id)">activation</el-button>
              </template>
            </el-table-column>
          </el-table>
          <br />
          <el-pagination :currentPage="pagination.currentPage" :page-size="pagination.pageSize"
            :page-sizes="[5, 10, 20, 40]" layout="total, sizes, prev, pager, next" :total="pagination.totalPages"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import api from "@/api/api.js";
export default {
  data() {
    return {
      phones: [],
      searchInfo: {
        phones: [],
        roles: [],
        createTime: "",
        startDate: "",
        endDate: "",
        status: "",
      },
      list: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        totalPages: 0,
      },
      multipleSelection: [],
    };
  },
  mounted() {
    this.getUserInfoList();
    this.getPhone();
  },
  methods: {
    //获取手机号
    getPhone() {
      api
        .findPhone()
        .then((response) => {
          if (response.code == "200") {
            this.phones = response.body;
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //查看用户信息
    getUserInfoList() {
      api
        .getUserInfoPages(
          this.pagination.currentPage,
          this.pagination.pageSize,
          this.searchInfo
        )
        .then((response) => {
          if (response.code == "200") {
            this.list = response.body.records;
            this.pagination.totalPages = response.body.total;
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //查看用户,用户的回显
    handleDetail(index, row) {
      this.$router.push("/systemManagement/userDetail");
      sessionStorage.setItem("id", row.id);
    },
    //删除问卷
    handleDelete(index, row) {
      this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api
            .deleteUserInfo(row.id)
            .then((response) => {
              if (response.code == "200") {
                this.getUserInfoList();
              }
            })
            .catch((error) => {
              console.log(error);
            });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //批量删除
    batchDelete() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择要删除的用户!",
        });
      } else {
        this.$confirm("此操作将永久删除这些用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            const ids = [];
            for (let i = 0; i < this.multipleSelection.length; i++) {
              ids.push(this.multipleSelection[i].id);
            }
            api
              .deleteBatchUserInfo(ids)
              .then((response) => {
                console.log(ids);
                console.log(response);
                if (response.code == "200") {
                  this.getUserInfoList();
                }
              })
              .catch((error) => {
                console.log(error);
              });
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    //多选选中
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //清空搜索条件
    resetForm(searchInfo) {
      this.$refs[searchInfo].resetFields(); //重置表单数据
      this.searchInfo.startDate = "",
        this.searchInfo.endDate = "",
        this.getUserInfoList();
    },
    //搜索表单信息
    searchForm() {
      if (this.searchInfo.createTime.length != 0) {
        this.searchInfo.startDate = this.searchInfo.createTime[0];
        this.searchInfo.endDate = this.searchInfo.createTime[1].replaceAll("00:00:00", "23:59:59")
      }
      console.log(this.searchInfo);
      this.getUserInfoList();
    },
    //导出为excel
    exportToExcel() {
      api
        .exportExcel(this.searchInfo)
        .then((res) => {
          let blob = new Blob([res], { type: "application/xlsx" });// 文件类型
          let url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");//创建a标签
          link.href = url
          link.download = "乳腺癌风险分析系统用户信息表.xlsx"; // 重命名文件
          link.click();
          URL.revokeObjectURL(url);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleSizeChange(pageSize) {
      this.pagination.pageSize = pageSize;
      this.getUserInfoList();
    },
    handleCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.getUserInfoList();
    },
    //冻结或激活用户
    handleLock(id, status) {
      api
        .frozenUser(id)
        .then((response) => {
          if (response.code == "200") {
            this.getUserInfoList();
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style scoped lang="scss">
.box-card {
  width: 90%;
  background: rgba(148, 185, 228, 0.062);
  border-radius: 8px;
  text-align: center;
  margin: auto;
}

.card-header {
  color: #080808;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card-title {
  font-size: 16px;
  font-weight: 600;
}

.el-card /deep/.el-card__header {
  background-color: #64bbe742;
  padding: 6px;
}
</style>